<template>
    <el-card shadow="never">
        <store-progress v-model="step" :progress="progress" :type="3" />
    </el-card>
    <el-card shadow="never" style="margin: 16px 0">
        <div class="content">
            <div class="storeTips">
                <store-tips :type="2" />
            </div>
            <div class="line"></div>
            <div v-show="step === 1" class="msg">
                <div class="title">
                    <span class="text">购买订单同步服务</span>

                    <!-- 外链暂时隐藏 -->
                    <el-button type="primary" size="small" :disabled="disabledFunc" @click="letsGo('youzhan_buy_app')"
                        >去购买</el-button
                    >
                </div>
                <div class="sync">
                    <div class="sync-title">请点击“去购买”，在打开的网页购买应用</div>
                    <div class="sync-img">
                        <el-image
                            src="https://static.scrm.keyid.cn/keyid-scrm-server/help/youzan_app_subscribe.png"
                            fit="cover">
                            <template #error>
                                <div class="image-slot">
                                    <el-icon><icon-picture /></el-icon>
                                </div>
                            </template>
                        </el-image>
                    </div>
                </div>

                <div class="title">
                    <span class="text">店铺基本信息</span>
                </div>
                <el-form
                    ref="storeBaseFormRef"
                    :model="storeBaseForm"
                    :rules="storeBaseFormRules"
                    label-width="auto"
                    :disabled="disabledFunc">
                    <el-form-item v-if="type == 'look'" label="客易达店铺ID" required disabled>
                        <el-input v-model="shop_id" />
                    </el-form-item>
                    <el-form-item label="店铺KDT ID" prop="external_shop_id">
                        <div class="withTips">
                            <el-input v-model="storeBaseForm.external_shop_id" placeholder="请输入店铺KDT ID" />

                            <!-- 外链暂时隐藏 -->
                            <span @click="letsGo('youzan_view_shop_id')">如何查看店铺KDT ID</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="店铺名称" prop="name">
                        <identify-name v-model="storeBaseForm.name" />
                    </el-form-item>
                    <el-form-item label="店铺logo" prop="logo">
                        <identify-logo v-model="storeBaseForm.logo" />
                    </el-form-item>
                </el-form>
            </div>

            <div v-show="step === 2" class="msg scroll">
                <div class="title">
                    <span class="text">数据配置</span>
                </div>
                <el-form
                    ref="storeSyncFormRef"
                    :model="storeSyncForm"
                    :label-width="140"
                    :rules="storeSyncFormRules"
                    :disabled="disabledFunc">
                    <el-form-item label="用户数据同步" prop="cust_sync">
                        <el-switch
                            v-model="storeSyncForm.cust_sync"
                            class="ml-2"
                            :active-value="1"
                            :inactive-value="2" />
                        <span style="font-size: 12px; padding-left: 4px">开启后，用户数据实时同步到客易达scrm</span>
                    </el-form-item>
                    <el-form-item label="订单数据同步" prop="order_sync">
                        <el-switch
                            v-model="storeSyncForm.order_sync"
                            class="ml-2"
                            :active-value="1"
                            :inactive-value="2" />
                        <span style="font-size: 12px; padding-left: 4px"
                            >开启后，上架订单数据将实时同步到客易达scrm</span
                        >
                    </el-form-item>
                    <el-form-item label="商品同步" prop="product_sync">
                        <el-switch
                            v-model="storeSyncForm.product_sync"
                            class="ml-2"
                            :active-value="1"
                            :inactive-value="2" />
                        <span style="font-size: 12px; padding-left: 4px"
                            >开启后，上架商品信息将实时同步到客易达scrm</span
                        >
                    </el-form-item>
                    <el-form-item v-if="storeSyncForm.product_sync == 1" label="有赞小程序AppId" prop="appid">
                        <div class="withTips">
                            <el-input v-model="storeSyncForm.appid" placeholder="请输入有赞小程序AppIdd" />

                            <!-- 外链暂时隐藏 -->
                            <!-- <span @click="letsGo('youzhan_view_applet_id')">如何查看有赞小程序AppIdd</span> -->
                        </div>
                        <div class="idTips">设置小程序Appid后，员工可通过侧边栏将小程序商品通过私信分享给客户</div>
                    </el-form-item>
                    <el-form-item label="用户行为数据同步" prop="behavior_sync">
                        <el-switch
                            v-model="storeSyncForm.behavior_sync"
                            class="ml-2"
                            :active-value="1"
                            :inactive-value="2" />
                        <span style="font-size: 12px; padding-left: 4px"
                            >开启后，用户行为数据将实时同步到客易达scrm</span
                        >
                    </el-form-item>
                </el-form>
            </div>

            <div v-show="step === 3" class="finishBox">
                <el-icon :style="{ fontSize: '60px' }" color="#60B900">
                    <CircleCheckFilled />
                </el-icon>
                <div v-if="type != 'look'">店铺创建成功</div>
                <div class="tag">您的客易达店铺ID为：{{ shop_id }} <span @click="copy(shop_id)">复制</span></div>
                <div v-if="open_platform == 1" class="tag">
                    请前往设置与开发去开启开发者功能 <span @click="toSetting">去配置</span>
                </div>
            </div>
        </div>
    </el-card>
    <div class="footer_button">
        <el-button v-if="step === 1" type="primary" @click="nextStep($event, true)">下一步</el-button>
        <template v-if="step === 2">
            <el-button @click="preStep">上一步</el-button>
            <el-button type="primary" @click="nextStep">下一步</el-button>
        </template>
        <template v-if="step === 3">
            <el-button @click="preStep">上一步</el-button>
            <el-button type="primary" @click="done">完成</el-button>
        </template>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import router from '@/router';
import { useRoute } from 'vue-router';
import { addStore, getYouzanInfo, getStoreDetail } from '@/api/ecommerce/storeManage';
import { commonLink, commonLinkList } from '@/api/channel/authconfig';
import storeProgress from '../components/storeProgress.vue';
import storeTips from '../components/storeTips.vue';
import identifyName from '../components/identifyName.vue';
import identifyLogo from '../components/identifyLogo.vue';

import lodash from 'lodash';
import useClipboard from 'vue-clipboard3';

import type { FormInstance, FormRules } from 'element-plus';

const routers = useRoute();
const { toClipboard } = useClipboard();
const { type } = routers.query;

const storeBaseFormRef = ref<FormInstance>();
const storeSyncFormRef = ref<FormInstance>();
const step = ref<number>(1);
const shop_id = ref<string>('');
const open_platform = ref<string | number>('');
const progress = ref<any>(['店铺授权', '数据配置', '完成']);
const links = ref<any>();

type storeBaseFormType = {
    external_shop_id: string;
    name: string;
    logo: string;
};
const storeBaseForm = reactive<storeBaseFormType>({
    // external_shop_id: '110620249',
    external_shop_id: '',
    name: '',
    logo: ''
});

/**
 * 是否禁用表单
 */
const disabledFunc = computed(() => {
    return type == 'look';
});

const validateID = async (rule: any, value: any, callback: any) => {
    if (!value) {
        storeBaseForm.name = '';
        storeBaseForm.logo = '';
        storeBaseFormRef.value.validateField('name');
        storeBaseFormRef.value.validateField('logo');
        callback(new Error('请输入店铺KDT ID'));
    } else {
        const params = { external_shop_id: value };
        const { is_match, name: name = '', logo: logo = '' } = await getYouzanInfo(params);
        if (is_match == 1) {
            //  1 匹配   2 不匹配
            storeBaseForm.name = name;
            storeBaseForm.logo = logo;
            storeBaseFormRef.value.validateField('name');
            storeBaseFormRef.value.validateField('logo');
            callback();
        } else {
            storeBaseForm.name = '';
            storeBaseForm.logo = '';
            storeBaseFormRef.value.validateField('name');
            storeBaseFormRef.value.validateField('logo');
            callback(new Error('未找到商家店铺信息，请检查店铺ID是否正确'));
        }
    }
};

const storeBaseFormRules = reactive<FormRules>({
    external_shop_id: [
        { required: true, message: '请输入店铺KDT ID', trigger: 'change' },
        { validator: validateID, trigger: 'blur' }
    ],
    name: [{ required: true, message: '请输入正确的店铺KDT ID', trigger: 'change' }],
    logo: [{ required: true, message: '请输入正确的店铺KDT ID', trigger: 'change' }]
});

type storeSyncFormType = {
    cust_sync: number;
    order_sync: number;
    product_sync: number;
    appid: string;
    behavior_sync: number;
};
const storeSyncForm = reactive<storeSyncFormType>({
    cust_sync: 1,
    order_sync: 1,
    product_sync: 1,
    appid: '',
    behavior_sync: 1
});
const storeSyncFormRules = reactive<FormRules>({
    appid: [{ required: false, message: '请输入有赞小程序AppIdd', trigger: 'change' }]
});

const letsGo = (type: string) => {
    const path = links.value[type].url;

    window.open(path, '_blank');
};

const nextStep = async ($e: MouseEvent, flag?: boolean): Promise<void> => {
    // 查看时不调用接口
    if (type == 'look') {
        if (step.value < 3) step.value++;
        return;
    }
    if (flag) {
        if (!storeBaseFormRef.value) return;
        await storeBaseFormRef.value.validate(async (valid: any): Promise<void> => {
            if (valid) {
                if (step.value < 3) step.value++;
            }
        });
    } else {
        if (!storeSyncFormRef.value) return;
        await storeSyncFormRef.value.validate(async (valid: any): Promise<void> => {
            if (valid) {
                if (step.value < 3) {
                    if (await addStoreCom()) {
                        step.value++;
                    }
                }
            }
        });
    }
};

const preStep = () => {
    if (step.value > 1) step.value--;
};

const done = () => {
    const path = '/ecommerce/storeManage/list';
    router.push(path);
};

const addStoreCom = async (): Promise<boolean> => {
    let params = lodash.cloneDeep(storeBaseForm);
    const params2 = lodash.cloneDeep(storeSyncForm);
    const source = Number(routers.query.source);
    const extr = {
        source
    };
    params = Object.assign({}, params, params2);
    params = Object.assign({}, params, extr);
    const { shop_id: shop_id_, open_platform: open_platform_ } = await addStore(params);
    if (shop_id_) {
        shop_id.value = shop_id_.toString();
        open_platform.value = open_platform_;
        return true;
    } else {
        return false;
    }
};

const copy = async (val: string) => {
    try {
        await toClipboard(val);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};
const toSetting = () => {
    const path = '/channelconfig/developConfiguration/basicConfiguration';
    router.push(path);
};

const height = computed(() => {
    const clientHeight = document.documentElement.clientHeight;
    return `${clientHeight - 380}px`;
});

/**
 * 获取店铺详情
 */
const getStoreDetails = async () => {
    const data = await getStoreDetail({ retail_shop_id: routers.query.shop_id });
    const { external_shop_id, name, logo, retail_shop_id, retail_shop_config } = data;
    storeBaseForm.external_shop_id = external_shop_id;
    storeBaseForm.name = name;
    storeBaseForm.logo = logo;
    const retail_shop_config_data = retail_shop_config;
    const { cust_sync, order_sync, product_sync, applet_app_id, behavior_sync } = retail_shop_config_data;
    storeSyncForm.cust_sync = cust_sync;
    storeSyncForm.order_sync = order_sync;
    storeSyncForm.product_sync = product_sync;
    storeSyncForm.appid = applet_app_id;
    storeSyncForm.behavior_sync = behavior_sync;
    shop_id.value = retail_shop_id;
};

onMounted(async () => {
    const codes = ['youzhan_buy_app', 'youzan_view_shop_id', 'youzhan_view_applet_id'];
    links.value = await commonLinkList({ codes });

    type == 'look' && getStoreDetails();
});
</script>
<style scoped lang="scss">
.footer_button {
    text-align: center;
    background-color: #fff;
    padding: 16px 24px;
    margin: 0 -16px -16px;
    border-top: 1px solid #eaeaea;
}

.content {
    display: flex;
    justify-content: space-between;

    // height: v-bind(height);
    height: calc(100vh - 339px);

    .withTips {
        display: flex;
        align-items: center;

        span {
            white-space: nowrap;
            text-indent: 12px;
            font-size: 12px;
            color: #ff6b00;

            &:hover {
                color: #f99547;
                cursor: pointer;
            }
        }
    }

    .idTips {
        font-size: 10px;
        color: #666;
        line-height: 1.6;
        margin-top: 8px;
    }

    .storeTips {
        flex: 1;
    }

    .line {
        width: 0;
        border-left: 1px dashed #eee;
        margin: 0 20px 0 8px;
    }

    .msg {
        flex: 1;
        height: v-bind(height);
        overflow: auto;
        padding-left: 10px;
        padding-right: 36px;
        box-sizing: border-box;

        .title {
            margin: 10px 0 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .text {
                text-indent: 8px;
                border-left: 3px solid #ff6b00;
            }
        }

        .sync {
            margin-bottom: 24px;

            .sync-title {
                font-size: 14px;
                color: #555;
                margin-bottom: 12px;
            }

            .sync-img {
                width: 100%;
                background-color: #fcfcfc;
                border: 1px solid #f8f8f8;

                .el-image {
                    width: 100%;
                    min-height: 300px;
                }
            }
        }

        .auth-step {
            margin-bottom: 20px;

            .step-header {
                display: flex;
                justify-content: space-between;
                align-items: center;

                span {
                    font-size: 13px;
                    font-weight: 500;
                    color: #555;
                }
            }

            .step-tips {
                display: flex;
                align-items: center;
                margin: 12px 0;
                padding-left: 16px;

                .tips-dot {
                    width: 8px;
                    height: 8px;
                    border-radius: 50%;
                    background-color: #ff6b00;
                }

                .tips-text {
                    text-indent: 6px;
                    font-size: 13px;
                    font-weight: 300;
                    color: #555;
                    line-height: 1.5;
                }
            }

            .step-img {
                width: 100%;
                height: 300px;
                background-color: #fcfcfc;

                img {
                    width: 100%;
                }
            }
        }
    }

    .scroll {
    }

    .finishBox {
        flex: 1;
        height: 500px;
        padding-left: 30px;
        padding-bottom: 100px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        & > div {
            line-height: 2;
            font-size: 12px;
            color: #555;
        }

        .tag {
            span {
                color: #ff6b00;

                &:hover {
                    cursor: pointer;
                }
            }
        }
    }
}

.next {
    display: flex;
    justify-content: flex-end;
}

.finished {
    display: flex;
    justify-content: flex-end;
}
</style>
